package media

import (
	"errors"
	"server/common"

	"github.com/mitchellh/mapstructure"
)

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) checkConsumeReqData(data common.CreateConsumerReqData) error {
	// Check if router ID is provided
	if data.RouterId == "" {
		return errors.New("router ID is required in consume request")
	}

	// Check if transport ID is provided
	if data.TransportId == "" {
		return errors.New("transport ID is required in consume request")
	}

	// Check if producer ID is provided
	if data.ProducerId == "" {
		return errors.New("producer ID is required in consume request")
	}

	// Check if kind is provided
	if data.Kind == "" {
		return errors.New("media kind is required in consume request")
	}

	// Check if rtp capabilities is provided
	if data.RtpCaps == nil {
		return errors.New("RTP parameters are required in consume request")
	}

	// Check if router exists
	if !s.RouterExists(data.RouterId) {
		return errors.New("router does not exist")
	}

	// Check if transport exists
	if !s.TransportExists(data.RouterId, data.TransportId) {
		return errors.New("transport does not exist in the router")
	}

	return nil
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) handleCreateConsumerReq(msg common.Message) {
	LOG(msg.Rid).WithField("msg", common.ToJson(msg)).Info("handling create consume request")

	var reqData common.CreateConsumerReqData
	if err := mapstructure.Decode(msg.Data, &reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to decode consume request data")
		return
	}

	if err := s.checkConsumeReqData(reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("consume request data validation failed")
		return
	}

	consumer, err := s.CreateConsumer(msg.Rid, reqData)
	if err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to create consumer")
		return
	}

	consumeResData := common.CreateConsumerResData{
		RouterId:      reqData.RouterId,
		ProducerId:    reqData.ProducerId,
		ConsumerId:    consumer.Id(),
		Kind:          consumer.Kind(),
		RtpParameters: consumer.RtpParameters(),
		AppData:       consumer.AppData(),
	}

	resMsg := common.Message{
		Cmd: common.CREATE_CONSUMER_RES,
		Rid: msg.Rid,
		Data: common.ResMsgData{
			Code: 0,
			Msg:  "consume request handled successfully",
			Data: consumeResData,
		},
	}

	if err := s.wsClient.Send(resMsg); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to send consume response")
	}
}
